<?php

namespace catchAdmin\phone\controller;

use catchAdmin\model\AliSms;
use catchAdmin\model\wechat\FuWuHaoApp;
use catchAdmin\model\wechat\MiniProgramApp;
use catchAdmin\model\WechatUser;
use catchAdmin\phone\request\login\CheckMobileCodeRequest;
use catchAdmin\phone\request\login\GetMobileCodeRequest;
use catchAdmin\phone\request\login\LoginRequest;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catcher\exceptions\AlertErrorException;
use thans\jwt\facade\JWTAuth;
use think\facade\Cache;

class Login extends CatchController
{

    public function getMobileCode(GetMobileCodeRequest $request)
    {
        $param = request()->param();

        return CatchResponse::success((new AliSms())->sendSmsCode([
            'mobile' => $param['mobile'],
        ]));
    }


    public function checkMobileCode(CheckMobileCodeRequest $request)
    {
        $param = request()->param();

        $cache_key = "code_" . $param['mobile'];
        $cache_code = Cache::get($cache_key);
        if (empty($cache_code)) {
            throw new AlertErrorException('验证码已过期');
        }

        if ($cache_code != $param['code']) {
            throw new AlertErrorException('验证码不正确');
        }

        Cache::delete($cache_key);

        return CatchResponse::success('验证成功');
    }


    /**
     * 小程序登陆
     */
    public function loginMini(LoginRequest $request)
    {
//        $wechat_user_msg = (new WechatUser())->where('id', 1)
//            ->find();
//
//        return CatchResponse::success($this->loginSuccess($wechat_user_msg));

        $param = request()->param();
        $mini_program_app = (new MiniProgramApp());

        $mini_user_msg = $mini_program_app->getUser($param['code']);
        if (empty($mini_user_msg['openid'])) {
            throw new AlertErrorException('授权异常');
        }

        // 1.查找openid
        $wechat_user_msg = (new WechatUser())
            ->where('mini_openid', $mini_user_msg['openid'])
            ->find();
        if (empty($wechat_user_msg)) {
            if (empty($mini_user_msg['session_key'])) {
                throw new AlertErrorException('授权异常');
            }

            $phone = (new MiniProgramApp())->getPhone([
                'session_key'   => $mini_user_msg['session_key'],
                'iv'            => $param['iv'],
                'encryptedData' => $param['encryptedData'],
            ]);

            // 2.查找手机号
            $wechat_user_msg = (new WechatUser())
                ->where('phone', $phone)
                ->find();
            if (empty($wechat_user_msg)) {
                $wechat_user_msg = (new WechatUser())->saveDataCC([
                    'mini_openid' => $mini_user_msg['openid'],
                    'phone'       => $phone,
                    'avatar'      => $param['avatar'] ?? "",
                    'nickname'    => $param['nickname'] ?? "",
                ]);
            }
        }

        return CatchResponse::success($this->loginSuccess($wechat_user_msg));
    }


    private function loginSuccess($wechat_user_msg)
    {
        return [
            'token'               => JWTAuth::builder([
                'id' => $wechat_user_msg['id'],
            ]),
            'company_type'        => $wechat_user_msg['company_type'],
            'company_type_name'   => $wechat_user_msg['company_type_name'],
            'company_status'      => $wechat_user_msg['company_status'],
            'company_status_name' => $wechat_user_msg['company_status_name'],
            'pay_can'             => 1,
        ];
    }


    /**
     * h5登陆
     */
    public function loginH5()
    {
        $param = request()->param();

        // 1.openid 登陆
        {
            $fu_wu_hao_app = (new FuWuHaoApp());
            $fwh_user_msg = $fu_wu_hao_app->getUserByCode($param['code']);

            $wechat_user_msg = WechatUser::where('openid', $fwh_user_msg['openid'])
                ->find();
            if (!empty($wechat_user_msg)) {
                return CatchResponse::success($this->loginSuccess($wechat_user_msg));
            }
        }

        // 2.手机号登陆
        if (!empty($param['phone'])) {
            $wechat_user_msg_phone = WechatUser::where('phone', $param['phone'])
                ->find();
            if (empty($wechat_user_msg_phone)) {
                throw new AlertErrorException('手机号未注册');
            }

            $wechat_user_msg_phone->openid = $fwh_user_msg['openid'];
            $wechat_user_msg_phone->save();
        }

        return CatchResponse::success($this->loginSuccess($wechat_user_msg));
    }

}
